package com.aa;

import java.util.ArrayList;



import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CallLogDetail extends Activity {

	private String TAG = "CallLogDetail";
	private Button mbtnBack;
	private TextView mtvAppCenter;
	private TextView mtvCallLogDetailName;
	private TextView mtvTimes;
	private ListView mListView;
	private LinearLayout mlaySMS;
	private LinearLayout mlayAddOrEdit;
	private LinearLayout mlayCall;
	private TextView mtvDelete;
	private String mNumber;
	private String mName;
	private boolean mbInPhone = false;
	private int miTimes = 0;
	private ArrayList<CallLogData> mCallLogDetailList =  new ArrayList<CallLogData>();
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.calllogdetail);
		initVarible();
		getDataArray();
		initView();
		bindData();
		initListener();
	}
	private void bindData(){
		CallLogDetailAdapter _CallLogDetailAdapter = new CallLogDetailAdapter(mCallLogDetailList);
		mListView.setAdapter(_CallLogDetailAdapter);
		mtvTimes.setText("" +miTimes);
	}
	private void initVarible(){
		mName = Common.iCallName;
		
		mNumber = getIntent().getStringExtra("number");
		if (mNumber.startsWith("+86")) {
			Common.iCallNumber = mNumber.substring(3, mNumber.length());
		}else {
			Common.iCallNumber = mNumber;
		}
		
		if (getIntent().getIntExtra("inphone", 0) == 1) {
			mbInPhone = true;		
		} 
	}
	private void initView(){
		mbtnBack = (Button)findViewById(R.id.title_btn1);
		mtvAppCenter = (TextView)findViewById(R.id.app_title_center);
		mtvCallLogDetailName = (TextView)findViewById(R.id.callogdetail_name);
		mtvTimes = (TextView)findViewById(R.id.callogdetail_times);
		mListView = (ListView)findViewById(R.id.calllogdetail_list);
		mlaySMS = (LinearLayout)findViewById(R.id.calllogdetail_sms_button);
		mlayAddOrEdit = (LinearLayout)findViewById(R.id.calllogdetail_edit_add);
		mtvDelete = (TextView)findViewById(R.id.calllogdetail_button_del);
		mlayCall = (LinearLayout)findViewById(R.id.calllogdetail_num_layout);
		if (!mbInPhone) {
			((TextView)findViewById(R.id.calllogdetail_edit_add_text)).setText(R.string.calllog_detail_add);
		}
		mtvAppCenter.setGravity(1);
		mtvAppCenter.setText(R.string.calllog_detail_title);
		mtvCallLogDetailName.setText(mName);
		
		mbtnBack.setText(R.string.app_back_tip);
		View _View = LayoutInflater.from(this).inflate(R.layout.calllog_detail_number_view, null);
		if (!mbInPhone) {
			 
		      ((TextView)_View.findViewById(R.id.contact_detail_number_type)).setText(getString(R.string.phone_type_other));
		      ((TextView)_View.findViewById(R.id.contact_detail_number_no)).setText(Common.iCallNumber);
		 }else {
			
		      ((TextView)_View.findViewById(R.id.contact_detail_number_type)).setText(getString(R.string.phone_type_mobile));
		      ((TextView)_View.findViewById(R.id.contact_detail_number_no)).setText(Common.iCallNumber);
		}
		((LinearLayout)_View.findViewById(R.id.calllog_detail_num_call_layout)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				submitCall();
				
			}
		});
		mlayCall.addView(_View);
	}
	private void initListener(){
		mlayCall.setOnClickListener(new OnCallLogDetailClickListener());
		mbtnBack.setOnClickListener(new OnCallLogDetailClickListener());
		mlayAddOrEdit.setOnClickListener(new OnCallLogDetailClickListener());
		mtvDelete.setOnClickListener(new OnCallLogDetailClickListener());
		
	}
	private void getDataArray()
	  {
	    ContentResolver _ContentResolver = getContentResolver();
	    Uri _Uri = CallLog.Calls.CONTENT_URI;
	    String[] arrayOfString1 = { "date", "number", "name", "type", "duration" };
	    String[] arrayOfString2 = new String[1];
	    arrayOfString2[0] = mNumber;
	    Cursor _Cursor = _ContentResolver.query(_Uri, arrayOfString1, "number=?", arrayOfString2, "date DESC");
	    startManagingCursor(_Cursor);
	    miTimes = _Cursor.getCount();
	    while (true)
	    {
	      if (!_Cursor.moveToNext())
	        return;
	      CallLogData _CallLogDa = new CallLogData();
	      _CallLogDa.number = _Cursor.getString(_Cursor.getColumnIndex("number"));
	      _CallLogDa.name = _Cursor.getString(_Cursor.getColumnIndex("name"));
	      _CallLogDa.date = _Cursor.getString(_Cursor.getColumnIndex("date"));
	      _CallLogDa.type = _Cursor.getString(_Cursor.getColumnIndex("type"));
	      _CallLogDa.duration = _Cursor.getInt(_Cursor.getColumnIndex("duration"));
	      if (_CallLogDa.number.equals("-2"))
	        _CallLogDa.number = getString(R.string.number_private);
	      if ((_CallLogDa.name == null) || (_CallLogDa.name.equals("")))
	        _CallLogDa.name = _CallLogDa.number;
	        mCallLogDetailList.add(_CallLogDa);
	    }
	  }
	

	 public void submitCall(){
		 Log.i(TAG, "iNativePhoneNumber = "+ Common.iNativePhoneNumber);
		 Log.i(TAG, "iCallNumber = "+ Common.iCallNumber);
		Common.InitCallSetData(this, 0);
//		if (Common.isSystemPhoneCall(Common.iCallNumber))
//		{
//		    Intent _Intent = new Intent();
//		    _Intent.setAction("android.intent.action.CALL");
//		    _Intent.setData(Uri.parse("tel:" + Common.iCallNumber));
//		    startActivity(_Intent);
//		    return;
//		 }
//		
		Intent _Intent = new Intent();
		_Intent.setClass(this, CallWaitActivity.class);
		startActivity(_Intent);
	 }
	 
	 private class OnCallLogDetailClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.calllogdetail_num_layout:
				submitCall();
				break;
			case R.id.title_btn1:
				finish();
				break;
			case R.id.calllogdetail_edit_add:
			if (mbInPhone)
	          {
	            ContentResolver _ContentResolver = getContentResolver();
	            Uri _Uri = ContactsContract.Contacts.CONTENT_URI;
	            String[] arrayOfString = new String[1];
	            arrayOfString[0] = mName;
	            Cursor _Cursor = _ContentResolver.query(_Uri, null, "display_name=?", arrayOfString, null);
	            if (_Cursor.moveToFirst())
	            {
	              String str = _Cursor.getString(_Cursor.getColumnIndex("lookup"));
	              Intent _Intent = new Intent("android.intent.action.EDIT", ContactsContract.Contacts.getLookupUri(_Cursor.getLong(_Cursor.getColumnIndex("_id")), str));
	              _Intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
	              _Intent.putExtra("addToDefaultDirectory", "");
	              startActivity(_Intent);
	            }
	          }else {
	        	  Intent _Intent = new Intent("android.intent.action.INSERT", ContactsContract.Contacts.CONTENT_URI);
	        	  _Intent.putExtra("phone", mNumber);
	              startActivity(_Intent);
			}
			case R.id.calllogdetail_button_del:
				 View _View = LayoutInflater.from(CallLogDetail.this).inflate(R.layout.dialog_title, null);
		          new AlertDialog.Builder(CallLogDetail.this).setCustomTitle(_View).setMessage(R.string.dialog_del_calllog)
		          .setNegativeButton(R.string.app_cancel, null
		          ).setPositiveButton(R.string.app_ok, new DialogInterface.OnClickListener()
		          {
		            public void onClick(DialogInterface paramAnonymous2DialogInterface, int paramAnonymous2Int)
		            {
		              ContentResolver _ContentResolver = CallLogDetail.this.getContentResolver();
		              Uri localUri = CallLog.Calls.CONTENT_URI;
		              String[] arrayOfString = new String[1];
		              arrayOfString[0] = mNumber;
		              if (_ContentResolver.delete(localUri, "number=?", arrayOfString) > 0)
		              {
		              
		                finish();
		                return;
		              }
		              Toast.makeText(CallLogDetail.this, R.string.calllog_detail_has_del_fail, 3000).show();
		            }
		          }).show();
		        
			default:
				break;
			}
			
		}
		 
	 }
	 public class ViewHolder
	  {
	    public TextView dateView;
	    public TextView durationView;
	    public TextView typeView;
   
	  }
	private class CallLogDetailAdapter extends BaseAdapter{

		private ArrayList<CallLogData> mList;
		public CallLogDetailAdapter(ArrayList<CallLogData> pList){
			mList = pList;
		}
		@Override
		public int getCount() {
			if (mList == null) {
				return 0;
			}
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			if (mList == null) {
				return null;
			}
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			CallLogData _CallLogData = (CallLogData)mList.get(position);
			ViewHolder _ViewHolder;
			if (convertView == null) {
				_ViewHolder = new ViewHolder();
				convertView = LayoutInflater.from(CallLogDetail.this).inflate(R.layout.calllogdetail_item, null);
				_ViewHolder.typeView = ((TextView)convertView.findViewById(R.id.calllogdetail_item_type));
				_ViewHolder.dateView = ((TextView)convertView.findViewById(R.id.calllogdetail_item_date));
				_ViewHolder.durationView = ((TextView)convertView.findViewById(R.id.calllogdetail_item_duration));
				convertView.setTag(_ViewHolder);
			}else {
				_ViewHolder = (ViewHolder)convertView.getTag();
			}
			 Long _Long = Long.valueOf(Long.parseLong(_CallLogData.date));
			 _ViewHolder.dateView.setText(DateUtils.getRelativeTimeSpanString(_Long.longValue(), System.currentTimeMillis(), 60000L,DateUtils.FORMAT_ABBREV_RELATIVE ));
			 if (_CallLogData.duration != 0) {
				 _ViewHolder.durationView.setText(String.valueOf(_CallLogData.duration) + CallLogDetail.this.getString(R.string.calllogdetail_sec));
			}else {
				_ViewHolder.durationView.setText(R.string.calllog_call_wjt);
			}
			 
			 if (_CallLogData.type != null && !_CallLogData.type.equals("")) {
				if (Integer.parseInt(_CallLogData.type) == 1 || Integer.parseInt(_CallLogData.type) == 3){
					_ViewHolder.typeView.setText(R.string.calllog_type_in);
				}else {
					_ViewHolder.typeView.setText(R.string.calllog_type_out);
				}
			}
			return convertView;
		}
		
	}
}
